package com.htjs.xxljobdemo.job;

import com.htjs.xxljobdemo.mapper.UserMobilePlanMapper;
import com.htjs.xxljobdemo.model.UserMobilePlan;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class SimpleXxlJob {
    private Logger logger = LoggerFactory.getLogger(SimpleXxlJob.class);

    @Autowired
    private UserMobilePlanMapper userMobilePlanMapper;

    @XxlJob("demoJobHandler")
    public void demoJobHandler() throws Exception {
        logger.info("执行定时任务,执行时间:"+new Date());
    }

    @XxlJob("sendMsgHandler")
    public void sendMsgHandler() throws Exception{
        List<UserMobilePlan> userMobilePlans = userMobilePlanMapper.selectAll();
        int shardingIndex = XxlJobHelper.getShardIndex();
        int shardingTotal = XxlJobHelper.getShardTotal();
        logger.info("shardingTotal:{}, shardingINdex:{}", shardingTotal, shardingIndex);
        Long startTime = System.currentTimeMillis();
        userMobilePlans.forEach(item->{
            try {
                if(item.getId() % shardingTotal == shardingIndex) {
                    logger.info("处理了{} 数据", item.getId());
                    //模拟发送短信动作
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        logger.info("任务结束时间:"+new Date());
        logger.info("任务耗时:"+(System.currentTimeMillis()-startTime)+"毫秒");
    }
}
